import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_component_core/utils/base_component_utils.dart';

class BaseSelectYear extends StatefulWidget {
  /// 已选年份
  final int selectedAnnual;

  /// 结果返回
  final Function(int annual) onSelected;

  const BaseSelectYear({Key key, this.selectedAnnual, @required this.onSelected}) : super(key: key);

  @override
  _BaseSelectYearState createState() => _BaseSelectYearState();
}

class _BaseSelectYearState extends State<BaseSelectYear> {
  /// 滚动列表item的豪赌
  static final double itemHeight = 48;

  /// 系统颜色 黑 Color(0xff333333) 白：Color(0xffffffff) 黑白主题选中颜色为Color(0xFFFF004F)
  Color get systemColor => Theme.of(context).primaryColor == Colors.white ? Color(0xFF333333) : Theme.of(context).primaryColor;

  /// 当前选择的年份
  int currSelectedYear = -1;

  /// 当前日期
  DateTime get nowTime => DateTime.now();

  /// 年的索引
  int yearIndex;

  /// 控制器
  FixedExtentScrollController yearScrollController;

  //年数组
  List<int> yearList = [];

  @override
  void initState() {
    super.initState();
    if (widget.selectedAnnual != null) currSelectedYear = widget.selectedAnnual;
    if (currSelectedYear > nowTime.year + 5) currSelectedYear = nowTime.year + 5;
    setupData();
    initSelectedIndex();
  }

  @override
  void dispose() {
    yearScrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(left: 16, right: 16, bottom: 8),
      child: Column(
        children: [
          buildHead(),
          BaseComponentUtils.buildHorizontalDivider(),
          Expanded(child: buildYearPickerView()),
        ],
      ),
    );
  }

  Widget buildHead() {
    return Container(
      color: Colors.white,
      margin: EdgeInsets.symmetric(vertical: 4),
      height: 40,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          InkWell(onTap: onCancelEvent, child: Text('取消', style: Theme.of(context).textTheme.bodyText2.copyWith(fontSize: 14))),
          Expanded(child: SizedBox()),
          InkWell(onTap: onConfirmEvent, child: Text('确认', style: Theme.of(context).textTheme.bodyText2.copyWith(fontSize: 14, color: systemColor, fontWeight: FontWeight.bold))),
        ],
      ),
    );
  }

  Widget buildYearPickerView() {
    return Container(
      child: CupertinoPicker(
        itemExtent: itemHeight,
        scrollController: yearScrollController,
        children: buildYearWidget(),
        looping: false,
        selectionOverlay: Container(
          width: double.infinity,
          height: itemHeight,
          decoration: BoxDecoration(border: Border(top: BorderSide(color: Color(0xFFEFEFEF)), bottom: BorderSide(color: Color(0xFFEFEFEF)))),
        ),
        onSelectedItemChanged: (index) {
          yearIndex = index;
          currSelectedYear = yearList[yearIndex];
          setState(() {});
        },
      ),
    );
  }

  List<Widget> buildYearWidget() {
    List<Widget> yearListWidget = []; //先建一个数组用于存放循环生成的widget
    for (var item in yearList) {
      yearListWidget.add(Center(child: Text('$item年', style: TextStyle(color: Colors.black87, fontSize: 16), maxLines: 1)));
    }

    return yearListWidget;
  }

  /// 取消
  void onCancelEvent() {
    BaseRouterUtil.getInstance().pop();
  }

  /// 确认事件
  void onConfirmEvent() {
    widget.onSelected(currSelectedYear);
    BaseRouterUtil.getInstance().pop();
  }

  ///初始化数据
  void setupData() {
    for (int i = 1970; i <= DateTime.now().year + 5; i++) {
      yearList.add(i);
    }
  }

  ///初始化时间索引
  void initSelectedIndex() {
    final List uniqueYearList = Set.from(yearList).toList();

    ///获取索引
    if (currSelectedYear != null && currSelectedYear > 0) {
      setState(() {
        yearIndex = uniqueYearList.indexOf(currSelectedYear);
      });
    } else {
      ///没有传选中日期默认当前系统时间
      String year = DateTime.now().year.toString();

      setState(() {
        yearIndex = uniqueYearList.indexOf(year);
      });
    }

    yearScrollController = FixedExtentScrollController(initialItem: yearIndex);
  }
}
